package cn.tannn.ops.quartz.job;

import cn.tannn.ops.common.message.MessageSsl;
import cn.tannn.ops.message.service.WebHookService;
import cn.tannn.ops.nginx.service.DomainsService;
import cn.tannn.ops.quartz.annotation.Job;
import cn.tannn.ops.quartz.annotation.JobMeta;
import cn.tannn.ops.sys.domain.WorkerConfig;
import cn.tannn.ops.sys.entity.SysConfig;
import cn.tannn.ops.sys.service.SysConfigService;
import cn.tannn.ops.util.WebHookUtil;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

/**
 * 域名证书过期通知 - (根据{@link SysConfig#getData()#WorkerConfig} }决定通知那些数据)
 *
 * @author <a href="https://t.tannn.cn/">tan</a>
 * @version V1.0
 * @date 2024/8/27 上午9:36
 * @see <a href="https://www.yuque.com/tanning/yg9ipo/bnug8bglppneik2r#qeIdb">Spring Boot Quartz 的快速使用</a>
 */
@Slf4j
@Component
@Job(cron = "0 15 9,16 * * ?", jobName = "DomainSslJob")
@JobMeta(name = "域名证书过期通知", description = "域名证书")
public class DomainSslJob extends QuartzJobBean {

    private final DomainsService domainsService;
    private final WebHookService webHookService;
    private final SysConfigService sysConfigService;

    public DomainSslJob(DomainsService domainsService
            , WebHookService webHookService
            , SysConfigService sysConfigService) {
        this.domainsService = domainsService;
        this.webHookService = webHookService;
        this.sysConfigService = sysConfigService;
    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        log.debug("Executing  DomainSslJob");
        SysConfig sysConfig = sysConfigService.findWorkerConfig();
        WorkerConfig workerConfig = sysConfig.getData().to(WorkerConfig.class);
        domainsService.findsWebHookDomains(workerConfig.getDomainSslExpiryDay()).forEach(domains -> {
            try {
                if (domains.getWebhookId() != null) {
                    webHookService.findOnly("id", domains.getWebhookId())
                            .ifPresentOrElse(hook ->
                                            WebHookUtil.sendMessage(hook, new MessageSsl(domains))
                                    , () -> log.error("webhook可能被删除请确定后重试"));
                }
            } catch (Exception e) {
                log.error("{}域名证书过期通知失败", domains.getDomain(), e);
            }
        });
    }
}
